package com.example.mywiseelves.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.example.mywiseelves.view.ElvesView;

/**
 * @author ZJK
 * @date 2021 14
 * @description 漂浮窗口管理
 */
public class FloatWindowManager {
    private ElvesView elvesView;

    private static WindowManager mWindowManager;

    public FloatWindowManager(ElvesView elvesView) {
        this.elvesView = elvesView;
    }

    //成功的将悬浮球添加到了桌面，并设置好位置
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void addElvesView(Context context) {

        WindowManager windowManager = getWindowManager(context);
        //窗口宽度
        int screenWidth = windowManager.getDefaultDisplay().getWidth();
        //窗口高度
        int screenHeight = windowManager.getDefaultDisplay().getHeight();
        //参数
        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0+
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        params.x = screenWidth / 2;
        params.y = screenHeight / 2;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.LEFT | Gravity.TOP;
        params.format = PixelFormat.RGBA_8888;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        elvesView.setLayoutParams(params);
        windowManager.addView(elvesView, params);


    }

    //移除控件
    public void removeElvesView(Context context) {
        if (elvesView != null) {
            WindowManager windowManager = getWindowManager(context);
            windowManager.removeView(elvesView);
            elvesView = null;
        }
    }

    private static WindowManager getWindowManager(Context context) {
        if (mWindowManager == null) {

            mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        return mWindowManager;
    }
}
